package com.xoa.service.party;


import com.xoa.dao.party.MapOwnerinfoMapper;
import com.xoa.dao.party.OrgDepartmentMapper;
import com.xoa.dao.party.OrgPartyMemberMapper;
import com.xoa.dao.partyMember.PartyMemberMapper;
import com.xoa.model.party.OrgDepartment;
import com.xoa.model.party.OrgPartyMember;
import com.xoa.model.users.Users;
import com.xoa.util.ToJson;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrgPartyMemberService {

    @Autowired
    private OrgPartyMemberMapper orgPartyMemberMapper;

    @Resource
    private OrgDepartmentMapper orgDepartmentMapper;

    @Resource
    private MapOwnerinfoMapper mapOwnerinfoMapper;

    public ToJson selectByList(OrgPartyMember orgPartyMember, Integer page, Integer pageSize, Boolean userFlag) {
        ToJson toJson = new ToJson();
        BaseWrappers baseWrapper = new BaseWrappers();
        Map<String, Object> paMap = new HashMap<String, Object>();
        Map<String, Object> paMapcount = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(userFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        paMap.put("orgPartyMember", orgPartyMember);
        try {
            List<OrgPartyMember> list = orgPartyMemberMapper.selectByList(paMap);
            if (list.size() > 0) {
                toJson.setObj(list);
                toJson.setTotleNum(orgPartyMemberMapper.countAll());
                toJson.setMsg("ok");
                return toJson;
            }
        } catch (Exception e) {
            e.getMessage();
            toJson.setFlag(1);
            toJson.setMsg("error");
        }

        return toJson;
    }

    public ToJson insert(OrgPartyMember orgPartyMember, HttpServletRequest request) {
        ToJson json = new ToJson();
        try {
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            orgPartyMember.setTis1(user.getUserId());
            orgPartyMember.setTis2(sdf.format(new Date()));
            orgPartyMember.setTis3(user.getDeptId().toString());
            int count = orgPartyMemberMapper.insertSelective(orgPartyMember);
            if (count > 0) {
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg("err");
            e.printStackTrace();
        } finally {
            return json;
        }
    }

    @Autowired
    private PartyMemberMapper partyMemberMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    public ToJson delete(String opIds) {
        ToJson json = new ToJson();
        int coun = 0;
        try {
            String[] count = opIds.split(",");
            for (int i = 0; i <= count.length - 1; i++) {
                if (count[i] != null) {
                    int opId = Integer.valueOf(count[i]).intValue();
                    OrgPartyMember orgPartyMember = orgPartyMemberMapper.selectByPrimaryKey(opId);
                    if (orgPartyMember != null && orgPartyMember.getUserId() != null) {
                        partyMemberMapper.delByUserId(orgPartyMember.getUserId());
                    }
                    int t = orgPartyMemberMapper.deleteByPrimaryKey(opId);
                    coun += t;
                }

            }
            if (coun > 0) {
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setFlag(1);
            json.setMsg(e.getMessage());
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
            return json;
        }
    }

    public ToJson update(OrgPartyMember orgPartyMember) {
        ToJson json = new ToJson();
        try {
            int count = orgPartyMemberMapper.updateByPrimaryKeySelective(orgPartyMember);
            if (count > 0) {
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg("err");
            e.printStackTrace();
        } finally {
            return json;
        }
    }

    public ToJson select(OrgPartyMember orgPartyMember, Integer page, Integer pageSize, Boolean userFlag) {
        ToJson json = new ToJson();
        try {
            Map<String, Object> paMap = new HashMap<String, Object>();
            Map<String, Object> paMapcount = new HashMap<String, Object>();
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(userFlag);
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            paMap.put("orgPartyMember", orgPartyMember);
            //paMap.put("pageParams",pageParams);
            paMapcount.put("orgPartyMember", orgPartyMember);
            List<OrgPartyMember> list = orgPartyMemberMapper.selectList(paMap);
            if (list != null && list.size() > 0) {
                OrgPartyMember OrgPartyMember = list.get(0);
                String location = OrgPartyMember.getAddressLocation();
                /*String name = mapOwnerinfoMapper.selectByLabelName(location);
                OrgPartyMember.setLabelName(name);*/
            }
            json.setFlag(0);
            if (list.size() > 0) {
                json.setObj(list);
                json.setTotleNum(pageParams.getTotal());
                json.setMsg("ok");
                return json;
            }
        } catch (Exception e) {
            json.setMsg("err");
            e.printStackTrace();
        }
        return json;
    }


    public ToJson ecoudInsert(MultipartFile file) {
        int count = 0;//計數器
        ToJson json = new ToJson();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");//判读当前系统
                    //读取配置文件
                    ResourceBundle rb = ResourceBundle.getBundle("upload");
                    String osName = System.getProperty("os.name");
                    StringBuffer path = new StringBuffer();
                    if (osName.toLowerCase().startsWith("win")) {
                        path = path.append(rb.getString("upload.win"));
                    } else {
                        path = path.append(rb.getString("upload.linux"));
                    }
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
//                    // 将文件上传成功后进行读取文件
//                    // 进行读取的路径
//                    String readPath = path.append(newFileName).toString();
//                    InputStream in = new FileInputStream(readPath);
                    InputStream in = file.getInputStream();
//                  得到所在位置

                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    OrgPartyMember orgPartyMember = null;
                    //得到ID

                    List<OrgDepartment> deptIdList = orgDepartmentMapper.selectByOrgDepartment();
                    for (int i = 1; i <= lastRowNum; i++) {
                        orgPartyMember = new OrgPartyMember();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //优秀党支部ID
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                cell.setCellType(CellType.STRING);
                                            }
                                            if (cell.getStringCellValue() != null && !"".equals(cell.getStringCellValue())) {
                                                for (OrgDepartment orgDepartment1 : deptIdList) {
                                                    if (orgDepartment1.getOrgDeptName().equals(cell.getStringCellValue())) {
                                                        orgPartyMember.setOrgDeptId(orgDepartment1.getOrgDeptId());
                                                    }
                                                }

                                            } else {
                                                orgPartyMember.setOrgDeptId(0);
                                            }
                                            break;
                                        case 1:
                                            //姓名
                                            orgPartyMember.setName(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //性别
                                            orgPartyMember.setSex(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //名族
                                            orgPartyMember.setFamilyName(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //出生日期
                                            orgPartyMember.setBirthday(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 5:
                                            //党员类型
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                cell.setCellType(CellType.STRING);
                                            }
                                            orgPartyMember.setMemberType(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 6:
                                            //入职日期
                                            String datim = null;
                                            if (cell.getStringCellValue() != null) {
                                                datim = cell.getStringCellValue();
                                            } else {
                                                datim = "";
                                            }
                                            orgPartyMember.setAdmissionDate(sdf.parse(datim));
                                            break;
                                        case 7:
                                            //工作岗位
                                            orgPartyMember.setPost(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 8:
                                            //学历
                                            orgPartyMember.setEducation(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 9:
                                            //联系方式
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                cell.setCellType(CellType.STRING);
                                            }
                                            orgPartyMember.setTel(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 10:
                                            //转正日期
                                        {
                                            String datim1 = null;
                                            if (cell.getStringCellValue() != null) {
                                                datim = cell.getStringCellValue();
                                            } else {
                                                datim = "";
                                            }
                                            orgPartyMember.setBecomeDate(sdf.parse(datim));
                                        }
                                        break;
                                        case 11:
                                            //党籍状态
                                            orgPartyMember.setPartyState(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 12:
                                            //家庭住址

                                            orgPartyMember.setAddress(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 13:
                                            //是否失联

                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                cell.setCellType(CellType.STRING);
                                            }
                                            if (cell.getStringCellValue() != null && !"".equals(cell.getStringCellValue())) {
                                                if ("是".equals(cell.getStringCellValue())) {
                                                    orgPartyMember.setContactNos("1");
                                                } else {
                                                    orgPartyMember.setContactNos("0");
                                                }
                                            } else {
                                                orgPartyMember.setFlowMemberNos("0");
                                            }
                                            break;
                                        case 14:
                                            //失联日期
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                cell.setCellType(CellType.STRING);
                                            }
                                            orgPartyMember.setContactDate(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 15:
                                            //是否为流动党员
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                cell.setCellType(CellType.STRING);
                                            }
                                            if (cell.getStringCellValue() != null && !"".equals(cell.getStringCellValue())) {
                                                if ("是".equals(cell.getStringCellValue())) {
                                                    orgPartyMember.setFlowMemberNos("1");
                                                } else {
                                                    orgPartyMember.setFlowMemberNos("0");
                                                }
                                            } else {
                                                orgPartyMember.setFlowMemberNos("0");
                                            }

                                            break;
                                        case 16:
                                            //外出流向
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                cell.setCellType(CellType.STRING);
                                            }
                                            orgPartyMember.setExtrMember(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            break;
                                        case 17:
                                            //位置坐标
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                cell.setCellType(CellType.STRING);
                                            }
                                            String memberTypeTo = mapOwnerinfoMapper.selectCoordingbyName(cell.getStringCellValue() == null ? "" : cell.getStringCellValue());
                                            orgPartyMember.setAddressLocation(memberTypeTo == null ? "" : memberTypeTo);
                                            break;

                                        default:
                                            json.setFlag(0);
                                            json.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            //将数据放入数据库
                            //如果没有找到社区不存入数据
                            int count1 = 0;
                            if (orgPartyMember.getOrgDeptId() != null && orgPartyMember.getOrgDeptId() != 0) {
                                count1 = orgPartyMemberMapper.insertSelective(orgPartyMember);
                            }
                            if (count1 > 0) {
                                count += count1;
                            }
                            dest.delete();

                        }
                    }

                }
            }
            if (count > 0) {
                json.setTotleNum(count);
                json.setMsg("ok");
                json.setFlag(0);
                return json;
            }
        } catch (Exception e) {
            json.setMsg("err");
            e.printStackTrace();
        } finally {
            return json;
        }
    }

    public ToJson selectOrgDeptandChDept(Integer orgDeptId) {
        ToJson toJson = new ToJson(0, "err");
        try {
            List<OrgDepartment> orgDepartments = orgDepartmentMapper.selectOrgDeptandChDept(orgDeptId);
            if (orgDepartments.size() > 0) {
                ArrayList arrayList = new ArrayList();
                for (OrgDepartment orgDepartment : orgDepartments) {
                    arrayList.add(orgDepartment.getOrgDeptId());
                }
                List<OrgPartyMember> list = orgPartyMemberMapper.selectByIds(arrayList);
                if (list.size() > 0) {
                    toJson.setObj(list);
                    toJson.setMsg("查询成功");
                } else {
                    toJson.setMsg("数据为空");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJson;
    }

    public ToJson selectByUserId(String userId) {
        ToJson toJson = new ToJson(0, "err");
        try {
            if (userId != null) {
                Integer count = orgPartyMemberMapper.selectByUserId(userId);
                toJson.setObject(count);
                toJson.setMsg("查询成功");
                toJson.setFlag(1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return toJson;
    }
}
